package com.itheima.appserver.service;

import cn.hutool.core.collection.CollUtil;
import com.itheima.appserver.exception.BusinessException;
import com.itheima.appserver.interceptor.UserHandler;
import com.itheima.dubbo.api.CommentApi;
import com.itheima.dubbo.api.UserInfoApi;
import com.itheima.model.domain.UserInfo;
import com.itheima.model.enums.CommentType;
import com.itheima.model.mongo.Comment;
import com.itheima.model.vo.CommentVo;
import com.itheima.model.vo.ErrorResult;
import com.itheima.model.vo.PageResult;
import com.itheima.utils.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CommentsService {
    @DubboReference
    private CommentApi commentApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //发布动态
    public void saveComments(String movementId, String comment) {
        //获取当前评论的用户id
        Long userId = UserHandler.getId();
        //构建comment
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(movementId));
        comment1.setCommentType(CommentType.COMMENT.getType());
        comment1.setContent(comment);
        comment1.setUserId(userId);
        comment1.setCreated(System.currentTimeMillis());
        //调用api保存,返回的是总条数,所以用int接收
        Integer counts = commentApi.save(comment1);
    }

    //分页查询条件
    public PageResult findComments(String movementId, Integer page, Integer pagesize) {
        //根据api查询分页列表
        List<Comment> list = commentApi.page(movementId, CommentType.COMMENT, page, pagesize);
        //判断集合是否为空
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //提取id,调用userinfoapi查询用户详情数据
        List<Long> ids = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids, null);

        //创建vo返回对象
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                vos.add(vo);
            }
        }
        //返回数据
        return new PageResult(page, pagesize, 0, vos);
    }

    public Integer hasComment(String id) {
        //调用api查询用户是否点赞
        Boolean result = commentApi.hasComment(id, UserHandler.getId(), CommentType.LIKE);
        //如果已经点赞抛出异常
        if (result) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //调用api保存
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(id));
        comment.setUserId(UserHandler.getId());
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setCreated(System.currentTimeMillis());
        Integer counts = commentApi.save(comment);
        //缓存到redis中,拼接key跟hashkey
        String key = Constants.MOVEMENTS_INTERACT_KEY + id;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHandler.getId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        //返回
        return counts;
    }

    public Integer unhasComment(String id) {
        //调用api查询用户是否点赞
        Boolean result = commentApi.hasComment(id, UserHandler.getId(), CommentType.LIKE);
        if (!result) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //删除数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(id));
        comment.setUserId(UserHandler.getId());
        comment.setCommentType(CommentType.LIKE.getType());
        Integer counts = commentApi.remove(comment);
        //删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + id;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHandler.getId();
        redisTemplate.opsForHash().delete(key, hashKey);
        return counts;
    }

    //点赞喜欢
    //喜欢
    public Integer loveComment(String movementId) {
        //1、调用API查询用户是否已点赞
        Boolean hasComment = commentApi.hasComment(movementId, UserHandler.getId(), CommentType.LOVE);
        //2、如果已经喜欢，抛出异常
        if (hasComment) {
            throw new BusinessException(ErrorResult.loveError());
        }
        //3、调用API保存数据到Mongodb
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHandler.getId());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.save(comment);
        //4、拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHandler.getId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return count;
    }

    //取消喜欢
    public Integer disloveComment(String movementId) {
        //1、调用API查询用户是否已点赞
        Boolean hasComment = commentApi.hasComment(movementId, UserHandler.getId(), CommentType.LOVE);
        //2、如果未点赞，抛出异常
        if (!hasComment) {
            throw new BusinessException(ErrorResult.disloveError());
        }
        //3、调用API，删除数据，返回点赞数量
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHandler.getId());
        Integer count = commentApi.remove(comment);
        //4、拼接redis的key，删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHandler.getId();
        redisTemplate.opsForHash().delete(key, hashKey);
        return count;
    }
}
